package com.kfdx.dc.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import com.kfdx.dc.common.exception.base.BaseException;
import com.kfdx.dc.system.config.file.FileConstant;
import com.kfdx.dc.system.config.file.TeaLocalUploadProperties;
import com.kfdx.dc.system.domain.SysFileEntity;
import com.kfdx.dc.system.service.ILocalUploadService;
import com.kfdx.dc.system.service.ISysFileService;
import org.apache.commons.codec.Charsets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import static cn.hutool.core.date.DatePattern.PURE_DATE_FORMAT;

@Service
public class LocalUploadServiceImpl implements ILocalUploadService {

    @Autowired
    TeaLocalUploadProperties teaLocalUploadProperties;

    @Autowired
    ISysFileService sysFileService;

    @Override
    public SysFileEntity uploadSingleFile(MultipartFile file, String type) {
        try {
            String filename = String.format(
                    "%s.%s",
                    IdUtil.getSnowflake().nextIdStr(),
                    FileNameUtil.extName(file.getOriginalFilename())
            );

            String path = String.format("%s/%s/%s",
                    type,
                    DateUtil.format(new Date(), PURE_DATE_FORMAT),
                    filename
            );

            FileUtil.writeFromStream(file.getInputStream(),
                    String.format("%s/%s", teaLocalUploadProperties.getLocalPath(), path));


            SysFileEntity saveObj = new SysFileEntity().setAttachementName(file.getOriginalFilename())
                    .setAttachementType(FileTypeUtil.getType(new File(String.format("%s/%s", teaLocalUploadProperties.getLocalPath(), path))))
                    .setAttachmentGroup("")
                    .setAttachementPath(path)
                    .setFileSize(file.getSize())
                    .setSaveType(FileConstant.TeaFileSaveTypeEnum.FILE_SAVE_LOCAL.getValue());
            sysFileService.insertSysFile(saveObj);
            return saveObj;

        } catch (IOException e) {
            throw new BaseException(String.format("上传文件%s失败", file.getOriginalFilename()));
        }
    }

    @Override
    public List<SysFileEntity> uploadMultiFile(MultipartFile[] multipartFiles, String type) {
        List<SysFileEntity> list = new LinkedList<>();
        for (MultipartFile multipartFile : multipartFiles) {
            list.add(uploadSingleFile(multipartFile, type));
        }
        return list;
    }

    @Override
    public InputStream downloadFile(HttpServletResponse response, String filePath) {
        try {
            BufferedInputStream inputStream = FileUtil.getInputStream(String.format("%s/%s", teaLocalUploadProperties.getLocalPath(), filePath));
            return inputStream;
        } catch (Exception e) {
        }
        return null;
    }

    @Override
    public String getFilePathByFileId(String fileId) {

        SysFileEntity sysFileEntity = sysFileService.selectSysFileById(Long.valueOf(fileId));
        if (sysFileEntity == null) {
            throw new BaseException("不存在的路径");
        }
        if (!FileConstant.TeaFileSaveTypeEnum.FILE_SAVE_LOCAL.getValue().equals(sysFileEntity.getSaveType())) {
            return teaLocalUploadProperties.getVisitAddress() + sysFileEntity.getAttachementPath();
        } else {
            return sysFileEntity.getAttachementPath();
        }
    }

    @Override
    public InputStream downloadFileById(HttpServletResponse response, Long fileId) {
        try {
            SysFileEntity sysFileEntity = sysFileService.selectSysFileById(fileId);
            String encodedfileName = cn.hutool.core.net.URLEncoder.createDefault().encode(sysFileEntity.getAttachementName(), Charsets.UTF_8);
            response.setCharacterEncoding("utf-8");
            response.setHeader("Access-Control-Expose-Headers", HttpHeaders.CONTENT_DISPOSITION);
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + encodedfileName);
            if (FileConstant.TeaFileSaveTypeEnum.FILE_SAVE_LOCAL.getValue().equals(sysFileEntity.getSaveType())) {
                BufferedInputStream inputStream = FileUtil.getInputStream(
                        String.format("%s/%s", teaLocalUploadProperties.getLocalPath(), sysFileEntity.getAttachementPath()));
                return inputStream;
            } else {
                return URLUtil.toUrlForHttp(sysFileEntity.getAttachementPath()).openStream();
            }





        } catch (Exception e) {
        }
        return null;
    }

    @Override
    public SysFileEntity uploadSingleFileNew(MultipartFile file, String type) {
        try {
            String filename = String.format(
                    "%s.%s",
                    IdUtil.getSnowflake().nextIdStr(),
                    FileNameUtil.extName(file.getOriginalFilename())
            );

            String path = String.format("%s/%s/%s",
                    type,
                    DateUtil.format(new Date(), PURE_DATE_FORMAT),
                    filename
            );

            FileUtil.writeFromStream(file.getInputStream(),
                    String.format("%s/%s", teaLocalUploadProperties.getLocalPath(), path));


            SysFileEntity saveObj = new SysFileEntity().setAttachementName(file.getOriginalFilename())
                    .setAttachementType(FileTypeUtil.getType(new File(String.format("%s/%s", teaLocalUploadProperties.getLocalPath(), path))))
                    .setAttachmentGroup("")
                    .setAttachementPath(path)
                    .setFileSize(file.getSize())
                    .setSaveType(FileConstant.TeaFileSaveTypeEnum.FILE_SAVE_LOCAL.getValue());
            sysFileService.insertSysFileNew(saveObj);
            return saveObj;

        } catch (IOException e) {
            throw new BaseException(String.format("上传文件%s失败", file.getOriginalFilename()));
        }
    }


}
